/**
 * Created by Foold on 14-2-15.
 */

/*
 * GET users listing.
 */
var cname  = require('path').basename(module.filename,'.js');
var routers = require('commons-dao')(cname);
var ObjectID = require('mongodb').ObjectID;
var form = require('express-form');
var field = form.field;

function getRules(i18n){

    return [
        field("articlec[id]").trim().required("",i18n.__('required','类别ID')),
        field("articlec[name]").trim().required("",i18n.__('required','类别名称')),
        field("createDate").trim().required("",i18n.__('required','创建时间')),
        field("content").trim().required("",i18n.__('required','内容'))
    ];

}

function preview(req,res,collection,db){
    var id= req.params.id;
    collection.findOne({'_id':new ObjectID(id)},function(err, doc) {

        if (err)  {
            res.send("error to connect db");
            return;
        }
        var rdata ={'bean':doc};
        res.render(cname+'/preview',rdata);
        db.close();
    });
}




function fromac(req,res,acol,db){

    var acid= req.params.cid;



    db.collection('articlec',function(err,arcCol){


        arcCol.findOne({_id:new ObjectID(acid)},function(err,doc){
            var rdata = routers.defaultBean;
            doc.id = doc._id;
            rdata.beans=JSON.stringify({articlec:doc});
            db.close();
            res.render(cname+'/input',rdata);
        });
    });

}

function forareac(req,res){

    var acid= req.params.cid;
    var area= req.params.area;
    var name =req.params.cname;
    var rdata = routers.defaultBean;
    var doc = {
        id:acid,
        name:name,
        area:area
    };
    rdata.beans=JSON.stringify({area:area,articlec:doc});

    res.render(cname+'/input',rdata);

}


module.exports = function(app,i18n){
    routers.init(app,getRules(i18n));
    app.get('/'+cname+'/preview/:id',function(req,res){
        routers.exterior(req,res,preview);
    });

    app.get('/'+cname+'/fromac/:cid',function(req,res){
        routers.exterior(req,res,fromac);
    });

    app.get('/'+cname+'/forarea/:area/:cid/:cname',function(req,res){
        routers.proxyHttp(req,res,forareac);
    });



}